<template>
	<view class="publish-container">
		<view class="input-title" style="margin-top: 20rpx;">描述</view>
		<view class="form-item">
			<text class="required">*</text>
			<input type="text" v-model="formData.des" placeholder="简要描述你您的房源" required />
		</view>

		<view class="input-title" style="margin-top: 20rpx;">房面积(单位㎡)</view>
		<view class="form-item">
			<text class="required">*</text>
			<input type="number" v-model="formData.area" placeholder="房屋大小单位㎡" required />
		</view>

		<view class="input-title">房屋状态</view>
		<view class="form-item">
			<text class="required">*</text>
			<input type="text" v-model="formData.houseState" placeholder="请选择房屋状态" @click="showHouseSelect" disabled />
		</view>

		<view class="input-title">支付模式(例预付6个月，押金1个月)</view>
		<view class="form-item">
			<text class="required">*</text>
			<input v-model="formData.pageMode" placeholder="请输入支付模式" />
		</view>

		<view class="input-title">租期(例剩余租期1个月)</view>
		<view class="form-item">
			<text class="required">*</text>
			<input v-model="formData.rentTime" placeholder="请输入租期" />
		</view>

		<view class="input-title">租金(例3w每月或面议)</view>
		<view class="form-item">
			<text class="required">*</text>
			<input v-model="formData.rentMoney" placeholder="请输入租金" />
		</view>

		<view class="input-title">转让费(例3w或无)</view>
		<view class="form-item">
			<text class="required">*</text>
			<input v-model="formData.transferMoney" placeholder="请输入转让费" />
		</view>


		<view class="input-title">省份</view>
		<view class="form-item">
			<text class="required">*</text>
			<input v-model="formData.province" placeholder="请选择省份" @click="showProvinceSelect" disabled />
		</view>

		<view class="input-title">城市</view>
		<view class="form-item">
			<text class="required">*</text>
			<input type="text" v-model="formData.city" placeholder="请选择城市" @click="showCitySelect" disabled />
		</view>

		<view class="input-title">区县</view>
		<view class="form-item">
			<text class="required">*</text>
			<input v-model="formData.district" placeholder="请选择区县" @click="showRegionSelect" disabled />
		</view>

		<view class="input-title">详细地址</view>
		<view class="form-item">
			<text class="required">*</text>
			<input type="text" v-model="formData.address" placeholder="请输入详细地址" />
		</view>

		<view class="input-title">联系电话</view>
		<view class="form-item">
			<text class="required">*</text>
			<input type="number" v-model="formData.phone" placeholder="请输入联系电话" />
		</view>

		<view class="image-upload multiple">
			<text class="input-title">更多图片（最多9张）</text>
			<view class="image-list">
				<view v-for="(img, index) in formData.images" :key="index" class="image-item">
					<image :src="img" mode="aspectFill"></image>
					<text class="delete-btn" @tap="deleteImage(index)">×</text>
				</view>
				<view v-if="formData.images.length < 8" class="upload-btn" @tap="uploadImages">
					<text class="iconfont icon-add">+</text>
				</view>
			</view>
		</view>

		<button type="submit" class="submit-btn" @click="handleSubmit">发布</button>

		<cusSelectView ref="cusselectProvince" title="请选择" :options="provinceListData" @confirm="provinceSelectConfirm">
		</cusSelectView>

		<cusSelectView2 ref="cusselectCity" title="请选择" :options="cityListData" @confirm="citySelectConfirm">
		</cusSelectView2>

		<cusSelectView3 ref="regionSelectRef" title="请选择" :options="regionListData" @confirm="regionSelectConfirm">
		</cusSelectView3>

		<cusSelectView3 ref="houseStateSelectRef" title="请选择" :options="houseStateList"
			@confirm="houseStateSelectConfirm">
		</cusSelectView3>


	</view>
</template>
<script>
	import select_view from '../../../components/select_view.vue'
	import select_view2 from '../../../components/select_view.vue'
	import select_view3 from '../../../components/select_view.vue'
	import select_view4 from '../../../components/select_view.vue'
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	import md5 from 'js-md5'
	export default {
		components: {
			cusSelectView: select_view,
			cusSelectView2: select_view2,
			cusSelectView3: select_view3,
			cusSelectView4: select_view4

		},
		computed: {
			userInfo() {
				return store.userInfo
			}
		},
		onLoad(option) {
			this.type = option.type;
			this.publishId = option.publishId;
			if(this.type == 'edit') {
				this.getPublish();
			}
		},
		onShow: function() {
			this.getAllProvince();
		},
		onReady: function() {
			this.provinceSelectRef = this.$refs.cusselectProvince
			this.citySelectRef = this.$refs.cusselectCity
			this.regionSelectRef = this.$refs.regionSelectRef
			this.houseStateSelectRef = this.$refs.houseStateSelectRef

		},
		data() {
			return {
				type:'add',
				publishId: "",
				formData: {
					province: '',
					houseState: '',
					city: '',
					district: '',
					community: '',
					address: '',
					coverImage: '',
					images: [],
				},
				uploadPath: [],

				provinceListData: [],
				provinceSelectRef: null,


				cityListData: [],
				citySelectRef: null,

				regionListData: [],
				regionSelectRef: null,

				houseStateSelectRef: null,

				houseStateList: [{
					id: '空置中',
					name: '空置中'
				}, {
					id: '空置中',
					name: "经营中"
				}],
			}
		},
		methods: {
			provinceSelectConfirm(content) {
				this.formData.province = content.name
				this.formData.provinceCode = content.code
				this.getAllCity();
			},

			citySelectConfirm(content) {
				this.formData.city = content.name
				this.formData.cityCode = content.code
				this.getAllRegion();
			},

			regionSelectConfirm(content) {
				this.formData.district = content.name
				this.formData.districtCode = content.code
			},

			houseStateSelectConfirm(content) {
				let that = this;

				setTimeout(() => {
					that.formData.houseState = content.name
				}, 500);
			
			},


			showProvinceSelect() {
				this.provinceSelectRef.show()
			},
			showCitySelect() {
				this.citySelectRef.show()
			},
			showRegionSelect() {
				this.regionSelectRef.show()
			},
			showHouseSelect() {
				this.houseStateSelectRef.show()
			},
			uploadCoverImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.formData.coverImage = res.tempFilePaths[0]
					}
				})
			},
			uploadImages() {
				uni.chooseImage({
					count: 9 - this.formData.images.length,
					success: (res) => {
						this.formData.images = [...this.formData.images, ...res.tempFilePaths]
					}
				})
			},
			deleteImage(index) {
				this.formData.images.splice(index, 1)
			},
			handleSubmit() {
				let that = this;
				uni.showLoading({
					title: '加载中'
				});
				this.uploadPath = [];
				let newsArr = this.formData.images.map(async item => {
					return await this.updateFunction(item)
				})
				Promise.all(newsArr).then(res => {
					that.toPublish()
				}).catch(err => {
					uni.hideLoading()
				})
			},
			// 批量上传到数据库
			updateFunction(item) {
				var names = item.split(".")
				var md5Name = md5(item) + "." + names[names.length - 1];
				this.uploadPath.push(md5Name)
				return uniCloud.uploadFile({
					filePath: item, //要上传的文件对象
					cloudPath: "user_image/" + md5Name, //cloudPath为云端文件名，
					cloudPathAsRealPath: true
				})
			},

			toPublish() {
				let that = this
				if (!that.formData.des) {
					uni.showToast({
						icon: 'none',
						title: "请输入描述",
					})
					return
				}

				if (!that.formData.province) {
					uni.showToast({
						icon: 'none',
						title: "请选择省份",
					})
					return
				}

				if (!that.formData.city) {
					uni.showToast({
						icon: 'none',
						title: "请选择城市",
					})
					return
				}

				if (!that.formData.district) {
					uni.showToast({
						icon: 'none',
						title: "请选择区",
					})
					return
				}

				if (!that.formData.address) {
					uni.showToast({
						icon: 'none',
						title: "请输入地址",
					})
					return
				}


				if (!that.formData.phone) {
					uni.showToast({
						icon: 'none',
						title: "请输入电话",
					})
					return
				}

				if (!that.uploadPath || that.uploadPath.length <= 0) {
					uni.showToast({
						icon: 'none',
						title: "请至少上传一张照片",
					})
					return
				}


				uniCloud.callFunction({
					name: 'page-main',
					data: {
						userName: that.userInfo.username,
						nickName: that.userInfo.nickname,
						userId: that.userInfo.username,
						des: that.formData.des,
						area: that.formData.area,
						houseState: that.formData.houseState,
						pageMode: that.formData.pageMode,
						rentTime: that.formData.rentTime,
						rentMoney: that.formData.rentMoney,
						transferMoney: that.formData.transferMoney,
						provinceName: that.formData.province,
						provinceCode: that.formData.provinceCode,
						cityName: that.formData.city,
						cityCode: that.formData.cityCode,
						districtName: that.formData.district,
						districtCode: that.formData.districtCode,
						address: that.formData.address,
						phone: that.formData.phone,
						publishDate: new Date().getTime(),
						publishImage: that.uploadPath.toString(),


						dataType: "add"
					},
					success(res) {
						uni.switchTab({
							"url": '/pages/tabBar/home/home'
						})
						uni.showToast({
							icon: 'none',
							title: "发布成功",
						})
						uni.hideLoading()
					},
					fail() {
						uni.hideLoading()
					}
				})
			},

			getAllProvince() {
				let that = this
				uniCloud.callFunction({
					name: 'page-common',
					data: {
						type: 0
					},
					success(res) {
						that.provinceListData = res.result.data
					},
					fail() {

					}
				})
			},

			getAllCity() {
				let that = this
				uniCloud.callFunction({
					name: 'page-common',
					data: {
						type: 1,
						parentCode: this.formData.provinceCode
					},
					success(res) {
						that.cityListData = res.result.data
					},
					fail() {

					}
				})
			},

			getAllRegion() {
				let that = this
				uniCloud.callFunction({
					name: 'page-common',
					data: {
						type: 2,
						parentCode: this.formData.cityCode
					},
					success(res) {
						that.regionListData = res.result.data
					},
					fail() {

					}
				})
			},
			
			getPublish() {
				let that = this
				that.imageList = [];
				uniCloud.callFunction({
					name: 'page-main',
					data: {
						dataType: "queryBy",
						publishId: this.publishId
					},
					success(res) {
						const detail = res.result.list[0];
						that.formData = res.result.list[0];
						that.formData.des = detail.publishDescription;
						that.formData.province = detail.provinceName;
						that.formData.city = detail.cityName;
						that.formData.district = detail.districtName;
						that.uploadPath = detail.publishImage.split(',')
					},
					fail() {
			
					}
				})
			},

		}
	}
</script>

<style>
	.text-select {
		height: 30rpx;
	}

	.publish-container {
		padding: 20rpx;
	}

	.form-item {
		margin-bottom: 20rpx;
		position: relative;
	}

	.required {
		color: #ff0000;
		position: absolute;
		left: -15rpx;
		top: 30rpx;
	}

	.input-title {
		color: #000000;
		margin-top: 15rpx;
	}

	input {
		border: 1px solid #aaa;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-top: 10rpx;
		color: #000000;

	}

	.image-upload {
		margin-bottom: 30rpx;
	}

	.image-upload text {
		display: block;
		margin-bottom: 10rpx;
	}

	.upload-btn {
		width: 200rpx;
		height: 200rpx;
		border: 1px dashed #ddd;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 60rpx;
		color: #999;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.image-item {
		position: relative;
		width: 200rpx;
		height: 200rpx;
	}

	.image-item image {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		right: -10rpx;
		top: -10rpx;
		width: 40rpx;
		height: 40rpx;
		background: rgba(0, 0, 0, 0.5);
		color: #fff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.submit-btn {
		margin-top: 40rpx;
		background: #007AFF;
		color: #fff;
	}

	.radio-container {
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: row;
		color: #999999;
	}

	.radio-title {
		display: block;
		margin-bottom: 10rpx;
	}

	.radio-group {
		display: flex;
		gap: 20rpx;
	}

	.radio-item {
		display: flex;
		align-items: center;
	}

	.radio-circle {
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		border: 1px solid #999;
		margin-right: 10rpx;
	}

	.radio-item.active .radio-circle {
		background-color: #007AFF;
	}
</style>